package cn.topevery.garden.wapi.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.topevery.garden.dal.logic.*;
import cn.topevery.garden.entity.po.Car;
import cn.topevery.garden.entity.po.CarFile;
import cn.topevery.garden.entity.query.CarQuery;
import cn.topevery.garden.entity.vo.CarVO;
import cn.topevery.garden.wapi.utils.DataUtils;
import com.github.dozermapper.core.Mapper;
import hw.topevery.basis.dal.logic.SysCompanyLogic;
import hw.topevery.basis.entity.po.SysCompany;
import hw.topevery.basis.entity.po.SysUser;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.util.ExcelUtil;
import hw.topevery.framework.web.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 
 *
 * @author code-generate
 * @date 2021-08-06
 */
@Api(tags = "")
@RestController
@RequestMapping("/car")
public class CarController extends BaseController {

    @Autowired
    ParkLogic parkLogic;

    @Autowired
    SectionLogic sectionLogic;
    
    @Autowired
    CarLogic carLogic;

    @Autowired
    CarFileLogic carFileLogic;

    @Autowired
    CarClassLogic carClassLogic;

    @Autowired
    Mapper mapper;

    @Autowired
    SysCompanyLogic companyLogic;

    /**
     * 获取分页列表
     *
     * @param query
     * @return
     */
    @ApiOperation(value = "获取页列表")
    @PostMapping("/getList")
    public JsonResult<DataPager<Car>> listPage(@RequestBody CarQuery query) {
        SysUser user = getUser();
        query.setDeptId(user.userIsAdmin==1?null:getSysDept().id.toString());
        DataPager<Car> page = carLogic.listPage(query);
        for(Car car : page.records){
            // 获取附件
            List<CarFile> fileList = carFileLogic.getListByPid(car.getId());
            car.setFileList(fileList);
            SysCompany entity = companyLogic.getEntity(car.getCompanyId());
            if(ObjectUtils.isNotEmpty(entity))
            {
                car.setCompanyName(entity.name);
            }
        }
        return JsonResult.ok(page);
    }

    @ApiOperation("新增/编辑 信息")
    @PostMapping("/save")
    public JsonResult<Boolean> saveOrUpdate(@Valid @RequestBody Car dto) {
        if (dto.getId() == null) {
            dto.setCarId(UUID.randomUUID().toString());
        }
        carLogic.saveOrUpdate(getUser().id.toString(),dto);

        // 保存附件
        carFileLogic.saveOrUpdate(getUser().id.toString(), dto.getId(), dto.getFileList());
        return JsonResult.ok(true);
    }

    @ApiOperation("获取详情")
    @GetMapping("/getInfoById")
    public JsonResult getInfoById(@RequestParam Integer id) {
        Car car = carLogic.getEntity(id);
        
        // 获取附件
        List<CarFile> fileList = carFileLogic.getListByPid(car.getId());
        car.setFileList(fileList);
        return JsonResult.ok(car);
    }

    @ApiOperation("根据自增ID批量删除")
    @GetMapping("/deleteInfoByIds")
    public JsonResult<Boolean> deleteBatchById(@RequestParam Integer[] ids) {
        carLogic.deleteBatchById(getUser().id.toString(),ids);
        return JsonResult.ok(true);
    }

    @ApiOperation("导入数据")
    @PostMapping("/importExcel")
    public JsonResult<Boolean> importExcel(@RequestBody MultipartFile file) throws Exception {
        JsonResult<Boolean> res = new JsonResult<Boolean>();
        try {
            ImportParams importParams = new ImportParams();
            importParams.setHeadRows(1);
            importParams.setNeedVerify(true);
            ExcelImportResult<CarVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), CarVO.class, importParams);
            List<CarVO> carVOList = result.getList();

            if(result.getFailList().size()>0){
                res.success=false;
                res.msg="校验存在不通过的数据行:"+String.join(",",result.getFailList().stream().map(CarVO::getCarNum).collect(Collectors.toList()));
            }
            else {

                //批量导入队列
                List<Car> carList = new ArrayList<>();
                //需要参与转换的数据源
                Map<String,Integer> sectionDic= DataUtils.ToMap(sectionLogic.getShortList(),"name","id");
                Map<String,Integer> parkDic=DataUtils.ToMap(parkLogic.getShortList(),"name","id");
                Map<String,Integer> personClassDic=DataUtils.ToMap(carClassLogic.getOptions(),"name","id");
                Map<Integer,String> workStateDic=DataUtils.getAnnotationExcelReplace(CarVO.class,"workState");
                Map<Integer,String> carColorDic=DataUtils.getAnnotationExcelReplace(CarVO.class,"carColorId");
                carVOList.forEach(f -> {
                    try {
                        if(personClassDic.containsKey(f.getTypeName())){
                            f.setType(personClassDic.get(f.getTypeName()));
                        }
                        if(sectionDic.containsKey(f.getSectionName())){
                            f.setSectionId(sectionDic.get(f.getSectionName()));
                        }
                        if(parkDic.containsKey(f.getParkName())){
                            f.setParkId(parkDic.get(f.getParkName()));
                        }
                        if(workStateDic.containsKey(f.getWorkState())) {
                            f.setWorkStateDesc(workStateDic.get(f.getWorkState()));
                        }
                        if(carColorDic.containsKey(f.getCarColorId())) {
                            f.setCarColorName(carColorDic.get(f.getCarColorId()));
                        }
                        //字典类数据转换
                        carList.add(mapper.map(f, Car.class));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
                carLogic.insert(getUser().id.toString(), carList);
                res.success = true;
            }
        }
        catch (Exception ex){
            res.success=false;
            res.msg="导入失败"+ex.getMessage();
        }
        return  res;
    }
    
    @ApiOperation("导出信息")
    @GetMapping("/export")
    public void export(CarQuery query, HttpServletResponse response) {
        List<Car> list = carLogic.listPage(query).records;
        ExcelUtil.exportExcel(list, "", "sheet1", Car.class, "", response);
    }

}
